<template>
  <div class="ai-chat-container">
    <div class="chat-messages" ref="messageContainer">
      <div v-for="(message, index) in chatHistory" :key="index" 
           :class="['message', message.role, { 'typing': message.isTyping }]">
        <div class="avatar">
          <a-avatar :src="message.role === 'user' ? userAvatar : aiAvatar" />
        </div>
        <div class="content">
          <div class="message-text" v-html="formatMessage(message.content || '...')"></div>
          <div class="timestamp">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>
    </div>
    
    <div class="chat-input-wrapper">
      <div class="chat-input">
        <a-textarea
          v-model:value="inputMessage"
          :rows="3"
          :auto-size="{ minRows: 1, maxRows: 4 }"
          placeholder="请输入您的问题..."
          @pressEnter.prevent="handleEnterPress"
          :disabled="loading"
        />
        <a-button 
          type="primary" 
          @click="sendMessage" 
          :loading="loading"
          :disabled="!inputMessage.trim()"
        >
          发送
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { marked } from 'marked'
import dayjs from 'dayjs'
import { debounce } from 'lodash-es'

const baseUrl = import.meta.env.VITE_APP_BASE_API 

interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
  timestamp: number
  isTyping?: boolean
}

const chatHistory = ref<ChatMessage[]>([])
const inputMessage = ref('')
const loading = ref(false)
const messageContainer = ref<HTMLElement | null>(null)
const userAvatar = '/path/to/user-avatar.png'
const aiAvatar = '/path/to/ai-avatar.png'

const handleEnterPress = (e: KeyboardEvent) => {
  if (e.shiftKey) {
    return; // 允许Shift+Enter换行
  }
  e.preventDefault();
  sendMessage();
}

const formatMessage = (content: string) => {
  const html = marked(content, {
    gfm: true,
    breaks: true,
    sanitize: false,
  })
  return html
}

const formatTime = (timestamp: number) => {
  return dayjs(timestamp).format('HH:mm')
}

const scrollToBottom = async () => {
  await nextTick()
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

const debouncedSendMessage = debounce(async () => {
  if (!inputMessage.value.trim() || loading.value) return
  
  const userMessage: ChatMessage = {
    role: 'user',
    content: inputMessage.value,
    timestamp: Date.now()
  }
  
  chatHistory.value.push(userMessage)
  const message = inputMessage.value
  inputMessage.value = ''
  loading.value = true
  
  await scrollToBottom()
  
  try {
    const assistantMessage: ChatMessage = {
      role: 'assistant',
      content: '',
      timestamp: Date.now(),
      isTyping: true
    }
    chatHistory.value.push(assistantMessage)
    
    const eventSource = new EventSource(`${baseUrl}/ai/chat/stream?input=${encodeURIComponent(message)}&uuid=13131jkfjlafa`)
    let buffer = ''
    let hasReceivedData = false
    
    const timeout = setTimeout(() => {
      if (!hasReceivedData) {
        eventSource.close()
        assistantMessage.content = '抱歉，我现在有点忙，请稍后再试...'
        assistantMessage.isTyping = false
        chatHistory.value = [...chatHistory.value]
        loading.value = false
        inputMessage.value = ''
      }
    }, 60000)
    
    eventSource.onmessage = (event) => {
      const data = event.data
      hasReceivedData = true
      
      if (data === '[DONE]') {
        clearTimeout(timeout)
        eventSource.close()
        assistantMessage.isTyping = false
        loading.value = false
        inputMessage.value = ''
        return
      }
      
      buffer += data
      assistantMessage.content = buffer
      chatHistory.value = [...chatHistory.value]
      scrollToBottom()
    }
    
    eventSource.onerror = (error) => {
      console.error('EventSource error:', error)
      clearTimeout(timeout)
      eventSource.close()
      
      if (!hasReceivedData) {
        assistantMessage.content = '连接出现错误，请重试...'
      }
      assistantMessage.isTyping = false
      chatHistory.value = [...chatHistory.value]
      loading.value = false
      inputMessage.value = ''
    }
    
  } catch (error) {
    console.error('发送消息失败:', error)
    loading.value = false
    inputMessage.value = ''
  }
}, 300)

const sendMessage = () => {
  debouncedSendMessage()
}

onMounted(() => {
//   chatHistory.value.push({
//     role: 'assistant',
//     content: '你好！我是AI助手，有什么可以帮你的吗？',
//     timestamp: Date.now()
//   })
    // inputMessage.value = '你好！'
    // sendMessage()
})

onUnmounted(() => {
  debouncedSendMessage.cancel()
})
</script>

<style scoped>
.ai-chat-container {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  padding: 20px;
  /* background: #f9fafc; */
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.message {
  display: flex;
  margin-bottom: 20px;
  gap: 12px;
}

.message.user {
  flex-direction: row-reverse;
}

.content {
  max-width: 70%;
  padding: 16px;
  border-radius: 12px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.message.assistant .content {
  background: #f0f7ff;
  border-bottom-left-radius: 4px;
}

.message.user .content {
  background: #1890ff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.user .timestamp {
  color: #ffffff99;
}

.message-text {
  line-height: 1.6;
  font-size: 14px;
  white-space: pre-wrap;
  word-break: break-word;
}

.message-text :deep(p) {
  margin: 0.5em 0;
}

.message-text :deep(code) {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.message-text :deep(pre) {
  background-color: #f6f8fa;
  padding: 1em;
  border-radius: 6px;
  overflow-x: auto;
  margin: 0.5em 0;
}

.message-text :deep(pre code) {
  background-color: transparent;
  padding: 0;
  font-size: 13px;
  line-height: 1.5;
}

.message.user .content .message-text {
  color: white;
}

.message.user .content .message-text :deep(code) {
  background-color: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.message.user .content .message-text :deep(pre) {
  background-color: rgba(255, 255, 255, 0.1);
}

.avatar :deep(.ant-avatar) {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.timestamp {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.chat-input-wrapper {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

.chat-input {
  display: flex;
  gap: 16px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  padding: 12px;
  position: relative;
}

.chat-input :deep(.ant-input) {
  flex: 1;
  min-height: 24px !important;
  max-height: 120px !important;
  padding: 12px 16px;
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  overflow-y: auto;
}

.chat-input .ant-btn {
  align-self: flex-end;
  height: 40px;
  padding: 0 24px;
  font-size: 14px;
  border-radius: 8px;
  white-space: nowrap;
}

.chat-input :deep(.ant-input:focus) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.chat-input :deep(.ant-input:hover) {
  border-color: #1890ff;
}

.chat-input .ant-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

/* 美化滚动条 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f5f7fa;
}

/* 添加打字机效果的动画 */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

.message.assistant .content {
  position: relative;
}

.message.assistant.typing .content::after {
  content: '';
  display: inline-block;
  width: 4px;
  height: 15px;
  background: #1890ff;
  margin-left: 5px;
  vertical-align: middle;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* 链接样式 */
.message-text :deep(a) {
  color: #1890ff;
  text-decoration: none;
}

.message.user .content .message-text :deep(a) {
  color: #fff;
  text-decoration: underline;
}

/* 列表样式 */
.message-text :deep(ul), .message-text :deep(ol) {
  padding-left: 1.5em;
  margin: 0.5em 0;
}

.message-text :deep(li) {
  margin: 0.25em 0;
}

/* 表格样式 */
.message-text :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 0.5em 0;
}

.message-text :deep(th), .message-text :deep(td) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.message-text :deep(th) {
  background-color: #f6f8fa;
}

/* 引用样式 */
.message-text :deep(blockquote) {
  margin: 0.5em 0;
  padding-left: 1em;
  border-left: 4px solid #ddd;
  color: #666;
}

.message.user .content .message-text :deep(blockquote) {
  border-left-color: rgba(255, 255, 255, 0.3);
  color: rgba(255, 255, 255, 0.9);
}

/* 优化打字机效果 */
.message.assistant.typing .content {
  position: relative;
}

.message.assistant.typing .content::after {
  content: '';
  display: inline-block;
  width: 4px;
  height: 15px;
  background: #1890ff;
  margin-left: 5px;
  vertical-align: middle;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* 加载中的消息样式 */
.message.assistant.typing .message-text {
  color: #8c8c8c;
}

.message.assistant.typing .content {
  background: #f5f5f5;
}
</style>
